package me.chan.netty.rpc.server.serialize;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *  replace by {@link SerializeAlgo}
 */
@Slf4j
public class JdkSerializer implements Serializer {

    @Override
    public <T> byte[] serialize(T t) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(t);
        return bos.toByteArray();
    }

    @Override
    public <T> T deserialize(Class<T> clazz, byte[] bytes) {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        T t = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(bis);
            t = (T) ois.readObject();
        } catch (ClassNotFoundException | IOException e) {
            log.error("{}", e);
        }
        return t;
    }
}
